package repository

import (
	"gitee.com/DevilYyx/pod/domain/model"
	"gorm.io/gorm"
)

type IPodRepository interface {
	// InitTable 初始化表
	InitTable() error
	// FindPodById 根据Id查找数据
	FindPodById(int64) (*model.Pod, error)
	// CreatePod 创建Pod
	CreatePod(*model.Pod) (int64, error)
	// DeletePodById 删除Pod
	DeletePodById(int64) error
	// UpdatePod 修改数据
	UpdatePod(*model.Pod) error
	// FindAll 查找所有数据
	FindAll() ([]model.Pod, error)
	// FindPodsByNameSpace 根据NameSpace查找数据
	FindPodsByNameSpace(string) ([]model.Pod, error)
	// 获取DB练级额
	GetDB() *gorm.DB
}

// 创建PodRepository

func NewPodRepository(db *gorm.DB) IPodRepository {
	return &PodRepository{db: db}
}

type PodRepository struct {
	db *gorm.DB
}

func (p *PodRepository) InitTable() error {
	return p.db.Migrator().AutoMigrate(&model.Pod{}, &model.PodEnv{}, &model.PodPort{})
}

func (p *PodRepository) FindPodById(id int64) (pod *model.Pod, err error) {
	pod = &model.Pod{}
	err = p.db.Preload("PodPort").Preload("PodEnv").First(pod, id).Error
	return pod, err
}

func (p *PodRepository) CreatePod(pod *model.Pod) (int64, error) {
	result := p.db.Create(pod)
	return pod.ID, result.Error
}

func (p *PodRepository) DeletePodById(id int64) (err error) {
	tx := p.db.Begin()
	// 类似与try-catch-finally 捕获异常回滚
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err = tx.Error; err != nil {
		return tx.Error
	}
	// 删除pod信息
	if err = p.db.Delete(&model.Pod{}, id).Error; err != nil {
		tx.Rollback()
		return err
	}
	// 删除podPort信息
	if err = p.db.Where("pod_id = ?", id).Delete(&model.PodPort{}).Error; err != nil {
		tx.Rollback()
		return err
	}
	// 删除podEnv信息
	if err = p.db.Where("pod_id = ?", id).Delete(&model.PodEnv{}).Error; err != nil {
		tx.Rollback()
		return err
	}
	return tx.Commit().Error
}

func (p *PodRepository) UpdatePod(pod *model.Pod) error {
	return p.db.Model(&model.Pod{}).Omit("id", "pod_namespace", "pod_name").Save(pod).Error

}
func (p *PodRepository) FindAll() (pods []model.Pod, err error) {
	return pods, p.db.Find(&pods).Error
}

func (p *PodRepository) FindPodsByNameSpace(namespace string) (pods []model.Pod, err error) {
	return pods, p.db.Where("pod_namespace = ?", namespace).Find(&pods).Error
}

func (p *PodRepository) GetDB() *gorm.DB {
	return p.db
}
